<?php

class Api_DbTable_Category extends Core_Db_Table_Abstract implements Core_Db_Crud_Interface
{
    /**
     * The default table name
     */
    const FILES_DIR = '/image/category/';
    protected $_name = 'categories';
    protected $_rowClass = 'Api_Row_Category';

    public function getTopLevel()
    {
        return $this->fetchAll($this->select()->where('parent_id = 0'));
    }

    public function getSubLevel(Api_Row_Category $category = null)
    {
        return $this->fetchAll($this->select()->where('parent_id = ?', $category->id));
        return $this->getSubLevel($r [0]);
    }

    public function getFirstSubCategory(Api_Row_Category $category = null)
    {
        $r = is_null($category) ? $this->getTopLevel() : $this->getSubLevel($category);
        if (count($r) == 0)
            return null;
        return $r [0];
    }

    public function getNested(Api_Row_Category $category = null)
    {
        $parent_id = is_null($category) ? ( int )0 : $category->id;

        return $this->fetchAll($this->select()->where('parent_id = ?', $parent_id));
    }

    public function getFirstNested($id)
    {
        if ($id !== 0) {
            $ $this->find($category->parent_id);
        } else
            return false;
    }

    public function find($id)
    {
        if (is_array($id))
            return parent::find($id);

        if (is_int($id) || (( int )$id > 0))
            return $this->fetchRow($this->select()->where('id = ?', ( int )$id));

        return null;
    }

    public function findAllSubcategory($parentid)
    {
        return $this->fetchAll($this->select()->where('parent_id = ?', ( int )$parentid));
    }

    public function getByProduct(Api_Row_Product $product)
    {
        return $this->find($product->parent_id);
    }

    public function getParent(Api_Row_Category $category)
    {
        return $this->find($category->parent_id);
    }

    public function getAll($parent = null)
    {
        $parent = ( int )$parent;
        $select = $this->select();

        if (!is_null($parent))
            $select->where('parent_id = ?', $parent);

        return $this->fetchAll($select);
    }

    public function getBackUrl($id, $type = 0)
    {
        $id = ( int )$id;
        $type = ( int )$type;

        switch ($type) {
            case 0 :
                {
                if ($id == 0)
                    return null;
                $parent_id = $this->find($id)->parent_id;
                break;
                }
            case 2 :
                $parent_id = $this->find($id)->parent_id;
                break;
            case 1 :
            case 3 :
                $parent_id = $id;
                break;
        }
        return Zend_Controller_Front::getInstance()->getRouter()->assemble(array("controller" => "admin", "action" => "read", "name" => "category", "id" => $parent_id), null, true);
    }

    public function getForm($id, $req = true)
    {
        $id = ( int )$id;
        return ($id === 0) ? new Api_Form_Category (null, null, $req) : new Api_Form_SubCategory (null, null, $req);
    }

    protected function _newName()
    {
        list ($usec, $sec) = explode(' ', microtime());
        mt_srand(( float )$sec + (( float )$usec * 100000));
        while (file_exists(self::FILES_DIR . 'big/' . ($name = md5(mt_rand())) . '.jpg')) {
        }
        return $name;
    }

    protected function _saveImg($name, $type, $new_name)
    {
        $prePath = APPLICATION_PATH . '/../public' . self::FILES_DIR;
        $img = new Core_Image ($name, 100);
        switch ($type) {
            case 'big' :
                $img->resize(100, 100);
                break;
            //case 'midle': $img->resize(165, 165); break;
            case 'small' :
                $img->resize(25, 25);
                break;
        }
        $file = $prePath . $type . '/' . $new_name . '.jpg';
        if (file_exists($file))
            unlink($file);
        $img->save($file);
        unset ($img);
    }

    public function create(Zend_Form $form, $parent = 0)
    {
        if ($parent == 0) {
            $name = $this->_newName();
            $this->_saveImg($_FILES ['img_src_1'] ['tmp_name'], 'big', $name);
            //$this->_saveImg($_FILES['img_src_2']['tmp_name'], 'midle', $name);
            $this->_saveImg($_FILES ['img_src_3'] ['tmp_name'], 'small', $name);

            $data = $form->getValues();
            $insert = array("title" => $data ['title'], "descript" => $data ['descript'], "parent_id" => 0, "img_src" => $name);
        } else {
            $data = $form->getValues();
            $insert = array('title' => $data ['title'], 'parent_id' => $parent);
        }

        $this->insert($insert);
    }

    protected function _deleteImage($src)
    {
        $prePath = APPLICATION_PATH . '/../public' . self::FILES_DIR;
        unlink($prePath . 'big/' . $src . '.jpg');
        //unlink($prePath . 'midle/' . $src . '.jpg');
        unlink($prePath . 'small/' . $src . '.jpg');
    }

    public function edit(Zend_Form $form, $id)
    {
        $row = $this->find($id);
        if ($row->parent_id == 0) {
            $src = $row->img_src;
            $newsrc = null;
            if (strlen($src) === 0)
                $src = $newsrc = $this->_newName();

            if (file_exists($_FILES ['img_src_1'] ['tmp_name']))
                $this->_saveImg($_FILES ['img_src_1'] ['tmp_name'], 'big', $src);

            //if(file_exists($_FILES['img_src_2']['tmp_name']))
            //$this->_saveImg($_FILES['img_src_2']['tmp_name'], 'midle', $src);


            if (file_exists($_FILES ['img_src_3'] ['tmp_name']))
                $this->_saveImg($_FILES ['img_src_3'] ['tmp_name'], 'small', $src);

            $data = $form->getValues();
            $insert = array("title" => $data ['title'], "descript" => $data ['descript']);
            if (!is_null($newsrc))
                $insert ['img_src'] = $newsrc;
        } else {
            $data = $form->getValues();
            $insert = array("title" => $data ['title']);
        }
        $this->update($insert, $this->getAdapter()->quoteInto('id = ?', $id));
    }

    public function getOne($id)
    {
        return $this->find($id);
    }

    public function getMetaData($id)
    {

        return (( int )$id === 0) ? array('image', 'title', 'description') : array('title');
    }

    public function remove($id)
    {
        $row = $this->find($id);
        if ($row->parent_id == 0) {
            $this->_deleteImage($row->img_src);
        }
        $this->delete($this->getAdapter()->quoteInto('id = ?', $id));
    }

    protected function _getIds()
    {
        return $this->fetchAll($this->select('id'))->toArray();
    }

    public function sync()
    {

    }
}
